<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">订单管理</h2>
      <el-button @click="refreshOrders" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card mb-3">
      <el-form :model="filterForm" inline>
        <el-form-item label="订单状态">
          <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
            <el-option label="待支付" value="PENDING" />
            <el-option label="已支付" value="PAID" />
            <el-option label="制作中" value="PREPARING" />
            <el-option label="待配送" value="READY" />
            <el-option label="配送中" value="DELIVERING" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="搜索">
          <el-input v-model="filterForm.keyword" placeholder="输入订单号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-table :data="orders" v-loading="loading" stripe>
        <el-table-column prop="orderNumber" label="订单号" width="160" />
        <el-table-column prop="customerName" label="客户" width="100" />
        <el-table-column prop="merchantName" label="商家" width="120" />
        <el-table-column prop="totalAmount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deliveryAddress" label="配送地址" show-overflow-tooltip />
        <el-table-column prop="createTime" label="下单时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewOrderDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="detailVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span class="label">订单号：</span>
            <span>{{ selectedOrder.orderNumber }}</span>
          </div>
          <div class="detail-item">
            <span class="label">下单时间：</span>
            <span>{{ formatTime(selectedOrder.createTime) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单状态：</span>
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">客户姓名：</span>
            <span>{{ selectedOrder.customerName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">商家名称：</span>
            <span>{{ selectedOrder.merchantName }}</span>
          </div>
          <div class="detail-item">
            <span class="label">配送地址：</span>
            <span>{{ selectedOrder.deliveryAddress }}</span>
          </div>
          <div class="detail-item">
            <span class="label">订单金额：</span>
            <span class="amount">¥{{ selectedOrder.totalAmount }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const orders = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const detailVisible = ref(false)
const selectedOrder = ref(null)

const filterForm = reactive({
  status: '',
  dateRange: null,
  keyword: ''
})

// 模拟订单数据
const mockOrders = [
  {
    id: 1,
    orderNumber: 'CD202412240001',
    customerName: '张同学',
    merchantName: '老王炒饭',
    totalAmount: 32.50,
    status: 'COMPLETED',
    deliveryAddress: '北京市朝阳区三里屯SOHO 1号楼101室',
    createTime: '2024-12-24 12:30:00'
  },
  {
    id: 2,
    orderNumber: 'CD202412240002',
    customerName: '李同学',
    merchantName: '刘记面馆',
    totalAmount: 28.00,
    status: 'DELIVERING',
    deliveryAddress: '北京市海淀区中关村大街1号',
    createTime: '2024-12-24 11:45:00'
  },
  {
    id: 3,
    orderNumber: 'CD202412240003',
    customerName: '王同学',
    merchantName: '老王炒饭',
    totalAmount: 45.80,
    status: 'PREPARING',
    deliveryAddress: '北京市东城区王府井大街1号',
    createTime: '2024-12-24 10:20:00'
  }
]

// 获取订单列表
const getOrders = async () => {
  try {
    loading.value = true
    
    // 筛选数据
    let filteredOrders = [...mockOrders]
    if (filterForm.status) {
      filteredOrders = filteredOrders.filter(o => o.status === filterForm.status)
    }
    if (filterForm.keyword) {
      filteredOrders = filteredOrders.filter(o => o.orderNumber.includes(filterForm.keyword))
    }
    
    total.value = filteredOrders.length
    const start = (currentPage.value - 1) * pageSize.value
    orders.value = filteredOrders.slice(start, start + pageSize.value)
    
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const refreshOrders = () => {
  currentPage.value = 1
  getOrders()
}

const handleSearch = () => {
  currentPage.value = 1
  getOrders()
}

const handleReset = () => {
  filterForm.status = ''
  filterForm.dateRange = null
  filterForm.keyword = ''
  currentPage.value = 1
  getOrders()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrders()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getOrders()
}

const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'PAID': 'info',
    'PREPARING': 'primary',
    'READY': 'success',
    'DELIVERING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    'PENDING': '待支付',
    'PAID': '已支付',
    'PREPARING': '制作中',
    'READY': '待配送',
    'DELIVERING': '配送中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return textMap[status] || '未知状态'
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const viewOrderDetail = (order) => {
  selectedOrder.value = order
  detailVisible.value = true
}

onMounted(() => {
  getOrders()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.order-detail {
  max-height: 500px;
  overflow-y: auto;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-light);
  padding-bottom: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
}

.detail-item .label {
  color: var(--text-regular);
  font-weight: 500;
  min-width: 100px;
}

.amount {
  color: var(--primary-color);
  font-weight: 600;
  font-size: 16px;
}
</style>
